﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Collections;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using System.Xml.Linq;

namespace MCCLGTelevisionService
{
    public partial class MCCLGTelevisionService : ServiceBase
    {
        private MCCLGTelevisionHost tvHost;

        public MCCLGTelevisionService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            this.tvHost = new MCCLGTelevisionHost();
            this.tvHost.Start();
        }

        protected override void OnStop()
        {
            this.tvHost.Stop();
        }
    }


    public class MCCLGTelevisionHost
    {
        private MediaCenterCommander.LGTelevision.LGTelevisionController tvController;

        public MCCLGTelevisionHost()
        {            
        }
        
        public void Start()
        {
            // TODO: Allow TCP port to be configured.
            // TODO: Load COM port from settings.

            IDictionary props = new Hashtable();
            props["name"] = "tcp4";
            props["port"] = 9900;
            props["bindTo"] = "127.0.0.1";
            TcpChannel tcpChannel = new TcpChannel(props, null, null);
            ChannelServices.RegisterChannel(tcpChannel, false);
            
            this.tvController = new MediaCenterCommander.LGTelevision.LGTelevisionController("COM3");
            RemotingServices.Marshal(this.tvController, "ITelevisionController");

            var uris = tcpChannel.GetUrlsForUri("ITelevisionController");
            string uri = uris[0];

            // TODO: Save out address.
            Console.WriteLine(uri);
        }
        
        public void Stop()
        {
            if (this.tvController != null)
            {
                this.tvController.Dispose();
                this.tvController = null;
            }
        }
    }
}
